package cn.kgm.handler;

import cn.kgm.entity.Command;
import cn.kgm.enums.CommandTypeEnums;
import cn.kgm.result.Result;
import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.logging.Logger;

import static cn.kgm.enums.CommandTypeEnums.CHAT;
import static cn.kgm.enums.CommandTypeEnums.CONNECTION;

/**
 * @author kappi
 * @kapi #技术改变自己#
 * @PACKAGE: cn.kgm.handler.WebSocketHandler
 * @EMAIL: Yolo.jk@qq.com
 * @DATE: 2023/4/16 15:53
 * @DAY_NAME_SHORT: 周日
 */
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static final Logger log = Logger.getLogger("WebSocketHandler");

    @Override
    protected void channelRead0(ChannelHandlerContext chc, TextWebSocketFrame frame){
        Command command = JSON.parseObject(frame.text(), Command.class);
        try {
            switch (CommandTypeEnums.match(command.getCode())) {
                case CONNECTION :{
                    ConnectionHandler.execute(chc, command);
                }
                case CHAT: {
                    ChatHandler.execute(chc,command);
                }
                default: chc.channel().writeAndFlush(Result.fail("未识别的指令 " + command.getCode()));
            }
        } catch (Exception e) {
            log.info("解析命令异常," + command.getCode());
            throw new RuntimeException("链接命令解析参数异常");
        }
    }
}
